package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.edu.annon.Autowired;
import com.lagou.edu.annon.Component;
import com.lagou.edu.annon.Repository;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author 应癫
 */
@Component
public class ConnectionUtils {


    @Autowired
    private DruidDataSource druidDataSource;

    private ThreadLocal<Connection> threadLocalConnection = new ThreadLocal<>();

    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        Connection connection = threadLocalConnection.get();
        if (null == connection){
            // 从连接池拿到连接 并绑定到线程
            connection = druidDataSource.getConnection();
            // 绑定到该线程
            threadLocalConnection.set(connection);
        }
        return connection;

    }
}
